package model;

import model.DBUtil;
import model.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    //注册
    public  void insert (User user){
        PreparedStatement statement=null;
        Connection connection=null;
        try {
            //连接数据库
            connection= DBUtil.getConnection();
            //构造SQL语句
            String sql="insert into user values(null,?,?)";
            statement=connection.prepareStatement(sql);
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());
            //执行SQL语句
            statement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(statement,connection,null);
        }
    }
   //根据用户名查找信息
    public User selectByName (String username){
        PreparedStatement statement=null;
        Connection connection=null;
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();
            String sql="select * from user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet =statement.executeQuery();
            //此处姓名是唯一的
            if(resultSet.next()){
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(statement,connection,resultSet);
        }
        return null;
    }
    //根据用户id查询用户信息
    public User selectById(int userId){
        PreparedStatement statement=null;
        Connection connection=null;
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();
            String sql="select * from user where userId=?";
            statement=connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet=statement.executeQuery();
            //此处的userId是主键
            if(resultSet.next()){
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(statement,connection,resultSet);
        }
        return null;
    }
}

